package com.xtxk.utils.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP地址
 * 
 */
public class IPUtils {
	private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
	
	private  static String  localIp="0:0:0:0:0:0:0:1";
	
	public  static String  localIpAddress="127.0.0.1";

	/**
	 * 获取IP地址
	 * 
	 * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
    	String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
        	logger.error("IPUtils ERROR ", e);
        }
        return "0:0:0:0:0:0:0:1".equals(ip)?"127.0.0.1":ip;
    }
	/**
	 * 获取MAC地址
	 * 
	 */
	public static String getMacAddress(String ipAddress) throws UnknownHostException, SocketException {
		if(org.apache.commons.lang3.StringUtils.isBlank(ipAddress)) {
			return null;
		}
		String line;
		String macAddress ="";
		final String LOOPBACK_ADDRESS ="127.0.0.1";
		if(ipAddress.equals(localIp)) {
			ipAddress = LOOPBACK_ADDRESS;
		}
		//如果为127.0.0.1，则获取本地的mac地址。
		if(LOOPBACK_ADDRESS.equals(ipAddress)) {
			InetAddress inetAddress = InetAddress.getLocalHost();
			byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
			//下面代码是把mac地址拼装成string
			StringBuilder sb = new StringBuilder();
			for(int i=0;i<mac.length;i++) {
				if(i != 0) {
					sb.append("-");
				}
			   //mac[i] & 0xFF是为了把byte转化为正整数
				String s =Integer.toHexString(mac[i] & 0xFF);
				sb.append(s.length() == 1?0+s:s);
			}
			//把字符串所有的小写字母改为大写成为正规的mac地址并返回
			macAddress = sb.toString().trim().toUpperCase();
			return  macAddress;
		}else {
			try {
				Process p = Runtime.getRuntime().exec("arp -A " + ipAddress);
				InputStreamReader ir = new InputStreamReader(p.getInputStream());
				BufferedReader br = new BufferedReader(ir);
				while((line = br.readLine()) != null) {
					/*if(str.indexOf("MAC") > 1) {
						macAddress = str.substring(str.indexOf("MAC")+9, str.length());
						macAddress = macAddress.trim();
						System.out.println("macAddress:"+macAddress);
						break;
					}*/
					if(line != null) {
						int index = line.indexOf(ipAddress);
						if(index != -1) {
							macAddress = line.substring(index+ipAddress.length()+10,index+ipAddress.length()+27).trim().toUpperCase();
						}
					}
				}
				p.destroy();
				br.close();
				ir.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(org.apache.commons.lang3.StringUtils.isBlank(macAddress)) {
				macAddress = ipAddress;
			}
			return macAddress;
		}
	}
	
	
	
	/**
	 * 获取运维服务器部署Ip地址
	 * @throws UnknownHostException 
	 */
	public static String getYwServiceIp() throws UnknownHostException {
		InetAddress  addr = InetAddress.getLocalHost();
		String localIp=addr.getHostAddress();
		return localIp;
	}
	
	public static void main(String[] args) throws UnknownHostException, SocketException {
		String mac = getMacAddress("172.16.3.51");
		System.out.println(mac);
	}
	
}
